// 自动释放过期台球桌
const cron = require('node-cron');
const { query } = require('../config/database');

cron.schedule('* * * * *', async () => {
  try {
    const now = new Date();
    const orders = await query(`
      SELECT o.table_id FROM orders o
      JOIN tables t ON o.table_id = t.id
      WHERE o.status = 'using'
        AND t.status = 'occupied'
        AND CONCAT(o.booking_date, ' ', o.end_time) < ?
    `, [now.toISOString().slice(0, 19).replace('T', ' ')]);

    for (const order of orders) {
      await query('UPDATE tables SET status = "available" WHERE id = ?', [order.table_id]);
    }

    if (orders.length > 0) {
      console.log(`[releaseTables] 已自动释放台球桌:`, orders.map(o => o.table_id));
    }
  } catch (err) {
    console.error('[releaseTables] 自动释放台球桌失败:', err);
  }
});

module.exports = {};